// Copyright (c) 2010 Manuel Peinado Gallego <manuel.peinado@gmail.com>
// Distributed under the MIT license

#include "stdafx.h"
#include "WorldBuilder.h"
#include "Sphere.h"
#include "Seg.h"
#include "Ray.h"
#include "AABB.h"


Sphere::Sphere(const gx::Vec3 & c, double r)
: center(c), radius(r)
{
}

bool Sphere::rayIntersection(const Ray & ray, double & dist2, gx::Vec3 & inter) const
{
    // TODO: make this. an op. of Ray (and replace it somewhere else where I also do it)
    Seg seg(ray.origin, ray.direction, 1e6);
    inter = seg.closestPnt(center);
    dist2 = inter.dist2(center);
    return dist2 < radius * radius;
}

Sphere applyTransform(const Sphere & sph, const gx::Mat4 & m)
{
    gx::Vec3 scale = m.rotation.get_scale();
    double s = fabs(scale.x) > fabs(scale.y) ? 
                (fabs(scale.x) > fabs(scale.z) ?  scale.x : scale.z)
                : (fabs(scale.y) > fabs(scale.z) ?  scale.y : scale.z);
    return Sphere(
        m * Pnt(sph.center), 
        sph.radius * s);
}

AABB Sphere::getAabb() const
{
    return AABB(SQRT_THREE * radius * gx::Vec3(1., 1., 1.), gx::zero);
}